package com.wc.data_structures.linkedlist;

/**
 * @Author congge
 * @Date 2023/4/19 19:56
 * @description 循环单链表
 */
public class CircleSingleLinkedListDemo {
    public static void main(String[] args) {
        CircleSingleLinkedList<Integer> list = new CircleSingleLinkedList<>();
        Node<Integer> node1 = new Node<>(1);
        Node<Integer> node2 = new Node<>(2);
    }
}

class CircleSingleLinkedList<T> {
    private Node<T> first;

    public CircleSingleLinkedList() {
        first = null;
    }

    public Node<T> getFirst() {
        return first;
    }

    public boolean isEmpty() {
        return first == null;
    }

    /**
     * 添加到头指针去
     *
     * @param node
     */
    public void addFirst(Node<T> node) {
        if (isEmpty()) {
            first = node;
            first.next = first;
            return;
        }
        Node<T> tmp = first.next;
        while (tmp.next != first) {
            tmp = tmp.next;
        }
        node.next = first;
        first = node;
        tmp.next = first;
    }

    /**
     * 在node1后添加node2
     *
     * @param node1
     * @param node2
     */
    public void addNode(Node<T> node1, Node<T> node2) {
        node2.next = node1.next;
        node1.next = node2;
    }

    /**
     * 删除node1
     *
     * @param node
     */
    public void deleteNode(Node<T> node) {
        if (first == node && first.next == first) {
            first = null;
            return;
        }
        Node<T> tmp = first.next;
        while (tmp.next != node) {
            tmp = tmp.next;
        }
        tmp.next = node.next;

        // 判断是不是删除的尾部
        if (node == first) {
            first = node.next;
        }
    }

    /**
     * 展示链表
     */
    public void showList() {
        if (isEmpty()) {
            System.out.println("链表无数据");
            return;
        }
        Node<T> tmp = first;
        System.out.print(tmp.value.toString() + " ");
        tmp = tmp.next;
        while (tmp != first) {
            System.out.print(tmp.value.toString() + " ");
            tmp = tmp.next;
        }
        System.out.println();
    }
}


